import axios from 'axios'
import qs from 'qs'
import { Toast } from 'vant'

export const http = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    // withCredentials: true
    timeout: 15000,
  })

  // 请求拦截器
http.interceptors.request.use(config => {
    //   config.headers['token'] = storage.get('token')
    return config
  }, error => {
    return Promise.reject(error)
  })

  // 响应拦截器
http.interceptors.response.use(response => {
    const data = response.data
    switch (data.code) {
      case "0":
        break
      case "100117": // token 过期
        Toast({
          message: data.msg||"服务器繁忙，请稍后重试。",
          position: 'middle',
          duration: 3000
        })
        routerJump("toLogin")
        break
      case "100118": // token 过期
        Toast({
          message: data.msg||"服务器繁忙，请稍后重试。",
          position: 'middle',
          duration: 3000
        })
        routerJump("toLogin")
        break
      case "100119": // 另外设备登录
        Toast({
          message: data.msg||"服务器繁忙，请稍后重试。",
          position: 'middle',
          duration: 3000,
        })
        routerJump("toLogin")
        break
    }
    return response
  }, error => {
    // Toast.clear()
    if (!error.response) {
      Toast({
        message: error.message,
        position: 'middle',
        duration: 3000,
      });
    }
    const resCode = error.response?error.response.status:-1
    switch (resCode) {
      case 500:
        Toast({
          message: '当前无网络，请检查网络设置',
          position: 'middle',
          duration: 3000,
        });
        break
      default:
        Toast({
          message: "网络不畅，请检查网络设置",
          position: 'middle',
          duration: 3000,
        });
    }
    return Promise.reject(error)
  })
  
  /**
   * 封装get方法，对应get请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
  function get(url, params = {}) {
    return new Promise((resolve, reject) => {
      http
        .get(url, {
          params: params
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
  
  /**
   * post方法，对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
  function post(url, params) {
    return new Promise((resolve, reject) => {
      http
        .post(url, qs.stringify(params))
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
  // JSON 请求 (formData)
  function json(url, params) {
    return new Promise((resolve, reject) => {
      http
        .post(url, params)
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
  
  export {
    get,
    post,
    json
  }